﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PromoCodes_Models.Entities;
using PromoCodes_Models.Abstract;

namespace PromoCodes_Models.Concrete
{
    public class EFPromotionRepository : IRepository<Promotion>
    {
        private EFDbContext context = EFDbContext.Context;
        public IQueryable<Promotion> Items
        {
            get { return context.Promotions.Include("Product"); }
        }

        public int Edit(Promotion item)
        {
            int idChanged = -1;
            if (item != null)
            {
                idChanged = item.PromotionID;
                if (item.PromotionID == 0)
                {
                    context.Promotions.Add(item);
                    context.SaveChanges();
                    idChanged = context.Promotions.First(p => p.PromotionCode == item.PromotionCode).PromotionID;
                }
                else
                {
                    context.Entry(context.Promotions.SingleOrDefault(p => p.PromotionID == item.PromotionID)).CurrentValues.SetValues(item);
                }
            }
            context.SaveChanges();
            //For debugging purposes...
            Promotion saved = context.Promotions.First(x => x.PromotionID == item.PromotionID);
            return idChanged;
        }

        public void Delete(Promotion item)
        {
            if (item != null)
                context.Promotions.Remove(item);
            context.SaveChanges();
        }
    }
}
